<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/8/28
 * Time: 下午5:22
 */
namespace app\common\model;

use think\Cache;
use think\Exception;
use think\exception\DbException;
use think\Model;
use think\Db;
use app\common\model\DeveloperException;
class Order extends Common
{
    /**
     * 生成订单编号
     *
     * @return string
     */
    static public function generateOrderSn()
    {
        return date("YmdHis") . random(4, true);
    }

    /**
     * @param $user  发起订单人
     * @param $money  现金
     * @param $coin  h币
     * @param $order_type 订单类型（1激活订单 2活动订单 3线下订单）
     * @param $receive_uid 收款方会员id
     * @param int $active_id 活动id
     * @param int $pay_type 支付类型
     * @param int $union_id 联盟商id
     * @param int $all_money 线下支付总钱数
     * @return array
     */

    static public function establish($user, $money,$coin,$order_type,$receive_uid,$active_id=0,$pay_type=0,$union_id=0,$all_money=0)
    {
        //订单编号
        $orderSn = self::generateOrderSn();

        $data=array(
            "uid" => $user["id"],
            "orderid" => $orderSn,
            "order_type" => $order_type,
            "pay_type" => $pay_type,
            "create_time" => time(),
            "pay_time" =>time(),
            "all_money" => $all_money,
            "coin" => $coin,
            "money" => $money,
            "active_id" => $active_id,
            "receive_uid" => $receive_uid,
            "union_id" => $union_id
        );

        //创建订单
        $orderId = Db::name("order")
            ->insertGetId($data);
        /*评论订单记录*/
        if($union_id>0)
        {
            Db::name('order_comment')
                ->insert(array(
                    'uid'=>$user['id'],
                    'order_id'=>$orderId,
                    'active_id'=>$active_id,
                    'union_id'=>$union_id,
                    'receive_uid'=>$receive_uid,
                    'star'=>5,
                    'content'=>"默认好评",
                    'comment_type'=>$order_type
                ));
        }

        return array(
            "order_id" => $orderId,
            "orderid" => $orderSn,
            "money" => number_format($money, 2),
            "coin" => number_format($coin, 2),
            "all_money" => number_format($all_money, 2)
        );
    }

    /**
     * 订单列表
     *
     */
    static public function orderList($user,$page,$page_size,$type,$is_evaluate="-1")
    {
        if($type==1)
        {
            if($is_evaluate=="-1")
            {
                $list=Db::name('order')
                    ->alias('o')
                    ->join("__ORDER_COMMENT__ c","o.id=c.order_id","left")
                    ->where('o.uid',$user['id'])
                    ->where('o.pay_status',1)
                    ->page($page,$page_size)
                    ->field('o.*,c.content as content,c.star as star')
                    ->select();
            }else{

                $list=Db::name('order')
                    ->alias('o')
                    ->join("__ORDER_COMMENT__ c","o.id=c.order_id","left")
                    ->where('o.uid',$user['id'])
                    ->where('o.pay_status',1)
                    ->where('o.is_comment',$is_evaluate)
                    ->page($page,$page_size)
                    ->field('o.*,c.content as content,c.star as star')
                    ->select();
            }
        }else{
            $list=Db::name('order')
                ->alias('o')
                ->join("__ORDER_COMMENT__ c","o.id=c.order_id","left")
                ->where('o.union_id',$user['id'])
                ->where('o.pay_status',1)
                ->page($page,$page_size)
                ->field('o.*,c.content as content,c.star as star')
                ->select();
        }


        if(!empty($list))
        {
            foreach ($list as &$item)
            {
                if($item['order_type']==1){
                    //激活订单
                    $item['union_name']="激活";
                }elseif ($item['order_type']==2){
                    $title = Db::name('active')->where('id',$item['active_id'])->value('title');
                    $item['union_name']='活动：'.$title;
                }else{
                    $title = Db::name('union')->where('id',$item['union_id'])->value('title');
                    $item['union_name']=$title;
                }
            }
        }

        return empty($list)?array():$list;

    }

    /**
     * 订单评价
     * @param  array $user 用户信息
     * @param int $orderid 订单id
     * @param string $star_num 评价星数
     * @param string $content 评价内容
     * @throws DbException
     * @throws DeveloperException
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\PDOException
     */
    static public function orderComment($user,$orderid,$star_num,$content)
    {
        $order=Db::name('order')
            ->where('uid',$user['id'])
            ->where('id',$orderid)
            ->find();
        if(empty($order))
        {
            throw new DeveloperException('不存在此订单！');
        }
        if($order['is_comment']!=1){
            throw new DeveloperException('无法重复评价订单！');
        }
        $star_num = intval($star_num);
        if($star_num>5 || $star_num<1){
            throw new DeveloperException('评价星级必须1-5星！');
        }

        /*修改订单状态*/
        Db::name('order')
            ->where('id',$orderid)
            ->update(array(
                "is_comment"=>"2"
            ));
        /*添加订单评论*/
        Db::name('order_comment')
            ->where('order_id',$orderid)
            ->where('uid',$user['id'])
            ->update(array(
                'star'=>$star_num,
                'content'=>htmlspecialchars($content),
                'comment_source'=>2,
                'comment_time'=>time()
            ));

    }

}

